﻿using System.Windows.Controls;
using System.Windows;
using Newtonsoft.Json;
using System.IO;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Data;
using System;
using System.Net;
using PenguinPublishNS.Models;
using Renci.SshNet;

namespace PenguinPublishNS.Views
{
    /// <summary>
    /// Interaction logic for HostSettings.xaml
    /// </summary>
    public partial class HostSettings : UserControl 
    {
        public string pPubPath = PenguinPublish.dataPath;
        public ObservableCollection<HostServer> myResults;
        public ICollectionView myView;
        private HostServer curHost;
        private ConnectionInfo sftpConnInfo;

        public HostSettings()
        {
            InitializeComponent();
            PenguinPublish._webMatrixHost.ShowNotification("my host settings are not here");

            if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                btnValidate.IsEnabled = false;
            }
            else
            {
                // txtNoNetwork.Visibility = Visibility.Collapsed;
                txtNoNetwork.Text = "No Network - Validate Disabled";
            }

            // TODO: Validate the .json file by comparing to the HostServer class type: see jsonUtils.jsonSchemaCheck()
            // Cannot do this with an array, but by using required attribute in HostServer class does validate the JSON file read in

            var streamR = new StreamReader(pPubPath + @"\dataHostSetting.json");
            myResults = JsonConvert.DeserializeObject<ObservableCollection<HostServer>>(streamR.ReadToEnd());
            streamR.Close();

            this.DataContext = myResults;
            this.cboHostNames.ItemsSource = myResults;
            myView = CollectionViewSource.GetDefaultView(myResults);
            // curHost = (HostServer)myView.CurrentItem;
        }

        public bool IsValidIPAddress(string addr)
        {
            IPAddress address;
            return IPAddress.TryParse(addr, out address);
        }

        private void txtIPaddress_LostFocus(object sender, RoutedEventArgs e)
        {
            string s = ((TextBox)sender).Text;
            Boolean bValid = IsValidIPAddress(s);
            if (!bValid) { MessageBox.Show("Invalid IP address"); }
            else
            {
                ((HostServer)myView.CurrentItem).ipAvailable = sftpUtils.chkHostIp(s);
                BindingOperations.GetBindingExpression(chkValidIP, CheckBox.IsCheckedProperty).UpdateTarget();
            }
        }

        
        private void cboHostNames_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (myView == null || myView.IsEmpty)
            {
                txtNoNetwork.Text = "Host Settings is Empty";
                return;
            }
            var hostID = ((ComboBox)sender).SelectedValue;
            myView.MoveCurrentToPosition(((ComboBox)sender).SelectedIndex);
            curHost = (HostServer)myView.CurrentItem;

        // ToDo: A thorough call of utility functions when changing the Host Setting we are currently on
            // Validate that the fields are all available before doing initializeSFTP

            if (curHost.hostName != null) // this is not enough. Other values are important and will be used
            {
                curHost.ipAvailable = sftpUtils.chkHostIp(curHost.HostAddress);
                BindingOperations.GetBindingExpression(chkValidIP, CheckBox.IsCheckedProperty).UpdateTarget();
                btnValidate.IsEnabled = curHost.ipAvailable;
                sftpConnInfo = sftpUtils.initializeSFTP(curHost.HostAddress, curHost.username, curHost.usePPK, curHost.password, curHost.keyPassphrase, curHost.privateKey);
            }

        }

        private void btnSaveSetting_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            string json = JsonConvert.SerializeObject(myResults, Formatting.Indented);
            File.WriteAllText(pPubPath + @"\dataHostSetting.json", json);
            addNewFolder(this.txtHostId.Text);
            // myView.MoveCurrentToPosition(((ComboBox)sender).SelectedIndex);
        }

        private void btnAddNew_Click(object sender, RoutedEventArgs e)
        {
            Guid newID = Guid.NewGuid();
            HostServer newServer = new HostServer { hostId = newID, usePPK = false };
            if (myResults == null)  // collection is empty in brand new project
            {
                myResults = new ObservableCollection<HostServer>();
                myView = CollectionViewSource.GetDefaultView(myResults);
            }
            myResults.Add(newServer);
            myView.MoveCurrentToLast();
            txtHostName.Focus();
        }

        private void addNewFolder(string newID)
        {
            DirectoryInfo di = Directory.CreateDirectory(pPubPath + @"/" + newID);
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            Directory.Delete(pPubPath + @"/" + this.txtHostId.Text, true);
            myResults.RemoveAt(myView.CurrentPosition);
            myView.Refresh();
        }


        private void btnValidate_Click(object sender, RoutedEventArgs e)
        {
            HostServer curHost = (HostServer)myView.CurrentItem;
            if (sftpUtils.checkFxs(sftpConnInfo, curHost.sitePath))
            {
                ((HostServer)myView.CurrentItem).sftpValid = true;
                BindingOperations.GetBindingExpression(chkHostValid, CheckBox.IsCheckedProperty).UpdateTarget();
                MessageBox.Show("All tests passed");
            }
        }

        private void UserControl_Unloaded_1(object sender, RoutedEventArgs e)
        {
            string json = JsonConvert.SerializeObject(myResults, Formatting.Indented);
            File.WriteAllText(pPubPath + @"\dataHostSetting.json", json);
            addNewFolder(this.txtHostId.Text);
        }

        private void cboHostNames_Loaded(object sender, RoutedEventArgs e)
        {
            cboHostNames_SelectionChanged(sender, null);
        }

    }
}
